const Koa = require('koa'),
  Logger = require('koa-logger'),
  Router = require('koa-router'),
  BodyParser = require('koa-body'),
  views = require('koa-render'),
  serve = require('koa-static'),
  path = require('path'),
  cors = require('koa2-cors');
  
const swagger = require('swagger2');
const swagger2Koa = require('swagger2-koa');
const app = new Koa(), port = 3000;


const mongoose = require('mongoose');

// Transform yaml file. [begin] {
const document = swagger.loadDocumentSync('./swagger.yaml');
// validate document
if (!swagger.validateDocument(document)) {
  throw Error(`./swagger.yml does not conform to the Swagger 2.0 schema`);
}
// Transform yaml file. [end] }

// Valid different origin query. [begin] {
app.use(
  cors({
      origin: function(ctx) {
          return 'http://localhost:8080'; //Allow requests from: http://localhost:8080
      },
      maxAge: 5, //指定本次预检请求的有效期，单位为秒。
      credentials: true, //是否允许发送Cookie
      allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
      allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
      exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  })
);
// Valid different origin query. [end] }

// Common middleware. [begin] {
app.use(Logger());
app.use(serve(path.join(__dirname, 'public')));
app.use(views('views', { default: 'ejs', extension:'ejs' }));
app.use(BodyParser());
// Common middleware. [end] }

// Validate request & response format. [begin] {
// app.use(swagger2Koa.validate(document));
// Validate request & response format. [end] {

const basePath = '/demo';
// Install controller. [begin] {
const newsController = require('./controller/news');
const apiRouter = newsController(new Router({
  prefix: basePath + '/news',
}));
const commentController = require('./controller/comment');
const commentRouter = commentController(new Router({
  prefix: basePath + '/comment',
}));

app
  .use(apiRouter.routes())
  .use(apiRouter.allowedMethods())
  .use(commentRouter.routes())
  .use(commentRouter.allowedMethods());
// Install controller. [end] {

// Install swagger-ui page. [begin] {
app.use(swagger2Koa.ui(document, '/doc'));
// Install swagger-ui page. [end] }

// Handle unknown request. [begin] {
app.use(async (ctx, next) => {
  ctx.body = await ctx.render('index', { title: 'Koa' });
});
// Handle unknown request. [end] }

mongoose.connect('mongodb://localhost/test', { useUnifiedTopology: true, useNewUrlParser: true }).then(function() {
  console.log('Connect mongo succesfully');
  const server = require('http').createServer(app.callback());
  const io = require('socket.io')(server);
  io.on('connection', function(socket) {
    const socketController = require('./controller/socket.js');
    socketController(socket);
  });
  server.listen(port, function() {
    console.log('Server running on port ' + port);
  });
}, function() {
  console.error('The server requires a valid mongoDB connection, checkout this.');
})

